import { reject } from 'lodash-es';
class NvrRpc {
  constructor() {}
  //定义静态方法
  static logIn = ({ ip, port, username, password }) => {
    return new Promise((resolve, reject) => {
      /**
       * RPC.login 登录
       * @param {string} $user.value 用户名
       * @param {string} $password.value 密码
       * @param {boolean} false 是否httpOnly,默认false
       * @returns {Promise}
       */

      let target = ip + ':' + port;
      window.setIP(target);
      window.RPC.login(username, password, false)
        .then((res) => {
          console.info('登录成功');
          window.RPC.keepAlive(300, 60000, window._getSession(), target);
          const browser = window.BrowserType();
          if (browser.includes('ie')) {
            window.onunload = () => {
              ajax({
                url: 'global.logout',
              });
            };
          } else if (browser.includes('chrome')) {
            const params = {
              method: 'global.logout',
              params: null,
              id: 10000,
              session: window._getSession(),
            };
            pubsub.subscribe('onbeforeunload', () => {
              navigator.sendBeacon('/RPC2', JSON.stringify(params));
            });
          } else {
            pubsub.subscribe('onbeforeunload', () => {
              ajax({
                url: 'global.logout',
              });
            });
          }
          resolve(res);
        })
        .catch((err) => {
          reject(err);
        });
    });
  };
  /**
   * 退出
   * @returns
   */
  static logOut = () => {
    return new Promise((resolve, reject) => {
      window.RPC.Global.logout()
        .then(function () {
          resolve();
        })
        .catch((err) => {
          reject(err);
        });
    });
  };
  /**
   * 获取所有的通道，码流
   * @returns
   */
  static getCameraAll = () => {
    return new Promise((resolve, reject) => {
      window.RPC.LogicDeviceManager.getCameraAll()
        .then(function (params) {
          console.log('数据params====', params);
          if (params.camera && params.camera.length > 0) {
            resolve(params.camera);
          } else {
            resolve([]);
          }
        })
        .catch((err) => {
          reject(err);
        });
    });
  };
  static logOut = () => {
    return new Promise(async (resolve, reject) => {
      window.RPC.Global.logout()
        .then(function () {
          resolve(true);
        })
        .catch((e) => {
          reject(e);
        });
    });
  };
  /**
   * 查询录像片段
   * @param {
   *   cameraChannel:原始通道号,
   *   startTimeL:开始时间,
   *   endTime:结束时间
   * }
   */
  static searchRecord = async ({ cameraChannel, startTime, endTime }) => {
    return new Promise(async (resolve, reject) => {
      let allRecords = [];
      let recordNums = 0;
      const getMediaFile = (params) => {
        return new Promise((resolve, reject) => {
          /**
           * RPC.MediaFileFind.instance 创建媒体文件查找实例
           * @returns {Promise}
           */
          RPC.MediaFileFind.instance()
            .then((json) => {
              let queryId = json.result;
              console.log('查询的queryId==', queryId);
              /**
               * RPC.MediaFileFind.findFile 设置查找条件，并判断是否存在文件
               * @param {number} queryId 实例id
               * @param {object} params condition参数
               * @returns {Promise}
               */
              RPC.MediaFileFind.findFile(queryId, params)
                .then(() => {
                  console.log('参数：：', queryId, params);
                  findNextFile(queryId)
                    .then(() => {
                      resolve(true);
                    })
                    .catch((err) => {
                      reject(err);
                    });
                })
                .catch((err) => {
                  reject(err);
                });
            })
            .catch((err) => {
              reject(err);
            });
        });
      };
      const findNextFile = (queryId) => {
        return new Promise((resolve, reject) => {
          /**
           * RPC.MediaFileFind.findNextFile 在指定条件基础上查询文件信息
           * @param {number} queryId 实例
           * @param {object} 需要查找的数目
           * @returns {Promise}
           */
          RPC.MediaFileFind.findNextFile(queryId, { count: 100 })
            .then((data) => {
              console.log('冲冲冲data=-===', data);
              if (Number.isInteger(data.found)) {
                recordNums = recordNums + data.found;
                allRecords = allRecords.concat([...data.infos]);
                if (data.found === 100) {
                  findNextFile(queryId)
                    .then(() => {
                      resolve(true);
                    })
                    .catch((err) => {
                      reject(err);
                    });
                } else {
                  stopFind(queryId);
                  resolve(true);
                }
              } else {
                stopFind(queryId);
                resolve(true);
              }
            })
            .catch((err) => {
              reject(err);
              stopFind(queryId);
            });
        });
      };
      const stopFind = (object) => {
        return new Promise((resolve, reject) => {
          /**
           * PC.MediaFileFind.close 结束查询
           * @param {number} object 媒体文件查找实例ID
           * @returns {Promise}
           */
          RPC.MediaFileFind.close(object)
            .then(() => {
              /**
               * PC.MediaFileFind.destroy 销毁媒体文件查找实例
               * @param {number} object 媒体文件查找实例ID
               */
              RPC.MediaFileFind.destroy(object);
              resolve(true);
            })
            .catch(() => {
              reject();
            })
            .finally(() => {});
        });
      };
      let tmpDir = [];
      try {
        /**
         * RPC.getDeviceAllInfo 获取存储信息
         * @param {string} 'getDeviceAllInfo' 方法名
         * @return {Promise}
         */
        tmpDir = await RPC.getDeviceAllInfo('getDeviceAllInfo');
      } catch (e) {
        console.log(e);
      }
      let dirs = null;
      if (tmpDir.info && tmpDir.info.length > 1) {
        dirs = 'All';
      } else {
        //dirs = tmpDir.info?[0]?.Detail?[0]?.Path ?? '/mnt/sd';
        dirs = (tmpDir.info && tmpDir.info[0] && tmpDir.info[0].Detail && tmpDir.info[0].Detail[0] && tmpDir.info[0].Detail[0].Path) || '/mnt/sd';
      }
      let params = {
        condition: {
          Channel: cameraChannel,
          Dirs: [dirs],
          StartTime: startTime,
          EndTime: endTime,
          Flags: null,
          Events: ['*'],
          Types: ['dav'],
        },
      };
      getMediaFile(params)
        .then(() => {
          resolve(allRecords);
        })
        .catch((err) => {
          if (err && err.error && err.error.code === 285409409) {
            reject(err);
          } else {
            resolve([]);
          }
        });
    });
  };
}

export default NvrRpc;
